<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $next) : Response
    {
		//权限验证
		$controller = $request->controller;
		$action = $request->action;

		//放过验证控制器-方法
		$letgoAry = [
			[
				'controller' => 'app\controller\Index',
				'action' => [
					'index',
					'login',
					'logout',
				]
			],
            [
                'controller' => 'app\controller\Home',
                'action' => [
                    'index',
                ]
            ],
		];
		if(!empty($letgoAry)){
			foreach($letgoAry as $k=>$vo){
				if($controller == $vo['controller'] && in_array($action,$vo['action'])){
                    print_r('[放过验证控制器+方法。'.$controller.'-'.$action.']');echo "\n";
					return $next($request);
				}
			}
		}

        //验证session
        $session = $request->session();
        if (!$session->get('token')) {
            print_r('session过期');
            return redirect('/');
        }

		if($session->get('roleId')==1){
            print_r('[超级管理 不验证权限。]');echo "\n";
			//超级管理 不严重权限
			return $next($request);
		}
		
		//验证操作权限
		$role_list = cache('role_list');
		if (!empty($role_list)) {
			$status = false;
			
			foreach($role_list as $key=>$val){
				if($session->get('roleId')==$val['id']){
					$basePurview = explode(',',$val['base_purview']);
					
					$controllerAry = explode('controller',strtolower($controller));
					$cf = substr($controllerAry[1],1) . '_' . $action;
					
					if (in_array($cf,$basePurview)){
						$status = true;
						break;
					}
				}
			}
			if($status == false){
                print_r('[暂无权限。'.$controller.'-'.$action.']');echo "\n";
				return return_json(0,'暂无权限');
			}
		}
        
        return $next($request);
    }
}
